package net.wwang.demo.controller;

import net.wwang.demo.config.security.MyPasswordEncoder;
import net.wwang.demo.dao.RoleDao;
import net.wwang.demo.dao.UserDao;
import net.wwang.demo.model.Role;
import net.wwang.demo.model.User;
import net.wwang.demo.utils.PhoneCode;
import net.wwang.demo.utils.RandomValidateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsProject: demo
 * @BelongsPackage: net.wwang.demo.controller
 * @Author: WangWei
 * @CreateTime: 2020-06-02 10:39
 * @Description:
 */
@Controller
public class IndexController {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;

    @Autowired
    MyPasswordEncoder passwordEncoder;

    @ResponseBody
    @RequestMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        RandomValidateCode randomValidateCode = new RandomValidateCode();
        try {
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @ResponseBody
    @RequestMapping("/checkCode")
    public Map<String,String> checkCode(@RequestParam("checkCode") String imageCode, HttpServletRequest request,
                                   HttpServletResponse response, HttpSession session) throws Exception {
        String verifyCode = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
        HashMap<String, String> result = new HashMap<>();
        if(!imageCode.equals(verifyCode)){
            result.put("errorInfo", "验证码填写错误!");
        }else{
            result.put("success", "true");
        }
        return  result;
    }
    @ResponseBody
    @RequestMapping("/checkLogin")
    public Map<String,String> checkLogin(@RequestParam("username") String name,@RequestParam("password") String pwd, HttpServletRequest request,
                                   HttpServletResponse response, HttpSession session) throws Exception {
        HashMap<String, String> result = new HashMap<>();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        User user = userDao.findUserByUsername(name);
       // int loginErro = 0;
       /* if(!checkLock(session, name)) {
            result.put("msg","用户已锁定，请联系管理员！或者30分钟后再尝试登录");
            return result;
        }*/
/*        if(user!=null||user.getLoginErro()>3){
            if(user.getLoginErro()>3){
                result.put("msg","用户已锁定，请联系管理员！");
                return result;}else {
            }
        }*/
        if(user!=null){
            boolean flag = encoder.matches(pwd, user.getPassword());
            if (flag){
                result.put("success", "true");
                result.put("msg","登陆成功！");
                cleanFailNum(session, name);
               /* loginErro = 0;
                user.setLoginErro(loginErro);
                userDao.saveAndFlush(user);*/
            }else {
                addFailNum(session, name);
                /*loginErro++;*/
                /*user.setLoginErro(loginErro);
                userDao.save(user);*/
                result.put("msg","密码错误请检查！");
            }
        }else{
           /* loginErro++;*/
            addFailNum(session, name);
            /*user.setLoginErro(loginErro);
            userDao.save(user);*/
            result.put("msg","用户名不存在请检查！");
        }
        return  result;
    }

    @PostMapping("/getCode")
    @ResponseBody
    public Map<String,String> getCode(@RequestParam("tel")String tel,HttpSession session){

        String phoneCode = PhoneCode.vcode();
        PhoneCode.getPhonemsg(tel,phoneCode);
        System.out.println("验证码"+phoneCode);
        session.setAttribute("phoneCode",phoneCode);
        Map<String,String> map = new HashMap<>();
        map.put("msg","验证码发送成功");
        return map;
    }

    @PostMapping("/register")
    @Transactional
    public String register(User user,@RequestParam("code")String code,HttpSession session){
        String phonemsg = (String)session.getAttribute("phoneCode");
        if(!phonemsg.equals(code)){
            Map<String,String> msg = new HashMap();
            msg.put("msg","验证码错误");
            return "user/userRegister";
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userDao.save(user);
        Role role = new Role();
        role.setName(user.getRole());
        role.setUsername(user.getUsername());
        roleDao.save(role);
        return "user/userLogin";
    }

    /**
     * 校验用户登录失败次数
     * @param session
     * @param username
     * @return
     */
    public boolean checkLock(HttpSession session,String username) {
        Object o = session.getServletContext().getAttribute(username);
        if(o==null) {
            return true;
        }
        HashMap<String,Object> map  = (HashMap<String, Object>) o;
        int num  = (int) map.get("num");
        Date date = (Date) map.get("lastDate");
        long timeDifference = ((new Date().getTime()-date.getTime())/60/1000);
        if(num>=3&&timeDifference<30) {
            return false;
        }
        return true;
    }
    /**
     * 新增用户登录失败次数
     * @param session
     * @param username
     */
    public void addFailNum(HttpSession session, String username) {
        Object o = session.getServletContext().getAttribute(username);
        HashMap<String,Object> map = null;
        int num= 0;
        if(o==null) {
            map = new HashMap<String,Object>();
        }else {
            map  = (HashMap<String, Object>) o;
            num  = (int) map.get("num");
            Date date = (Date) map.get("lastDate");
            long timeDifference = ((new Date().getTime()-date.getTime())/60/1000);
            if(timeDifference>=30) {
                num=0;
            }
        }
        map.put("num", num+1);
        map.put("lastDate", new Date());
        session.getServletContext().setAttribute(username, map);
    }
    /**
     * 清理用户登录失败的记录
     * @param session
     * @param username
     */
    public void cleanFailNum(HttpSession session, String username) {
        session.getServletContext().removeAttribute(username);
    }
}
